/*
Copyright (c) 2007 Roger Braun

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.*/
#include "stdio.h"
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_mixer.h"
#include "stdbool.h"


//Opens the file, allocates the memory for it and writes the pointer in **result.
//Returns the filesize in bytes.
int load_file_to_memory(const char *filename, Uint8 **result)
{
	int size = 0;
	FILE *f = fopen(filename, "rb");
	if (f == NULL) 
	{
		*result = NULL;
		return -1; // -1 means file opening fail
	}
	fseek(f, 0, SEEK_END);
	size = ftell(f);
	fseek(f, 0, SEEK_SET);
	*result = (Uint8*) malloc(size*sizeof(Uint8));
	if (size != fread(*result, sizeof(Uint8), size, f))
	{
		free(*result);
		return -2; // -2 means file reading fail
	}
	fclose(f);
	
	return size;
}

int main (int argc, char **argv)

{

	if(argc<2)
	{
		printf("usage: playraw rawfile.raw\n");
		return 1;
	}
  	SDL_Event event;
  	int status, key;
  	bool quit = false;
	printf("playraw:::trying to play the file\n");
	
	//Let's initialize the SDL
	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)<0)
	{
		printf("Could not initialize SDL");
	}

	SDL_Surface *screen;
	//Let's make a screen;
	screen = SDL_SetVideoMode(800, 600, 32,
                             SDL_HWSURFACE|SDL_DOUBLEBUF);	
	SDL_AudioSpec wav_spec;
	Uint32 wav_length;
	Uint8 *wav_buffer;

	//Format of the Ascendancy raw files:
	//8-Bit unsigned pcm
	Uint8 *music;                       //Pointer to our music, in memory
	Mix_Chunk *musicchunk;				//The music, translated to the format SDL knows
	int audio_rate = 22050;             //Frequency of audio playback
	Uint16 audio_format = AUDIO_U8;     //Format of the audio we're playing
	int audio_channels = 1;             //2 channels = stereo
	int audio_buffers = 4096*2;         //Size of the audio buffers in memory

  	//Initialize SDL_mixer with our chosen audio settings
  	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0)
  	{
    	printf("Unable to initialize audio: %s\n", Mix_GetError());
    	return 1;
  	}

	//Now load the raw file and hope it works
	Uint32 size = load_file_to_memory(argv[1],&music);
	
	if(size<0)
	{
		printf("An error occured while loading the file!\n");
	}
	
	printf("Filesize in bytes:%d\n",size);
	
	//Mix_QuickLoad_RAW is quite dangerous. It does little to know checking,
	//so if you want to play the readme, it will do that. It will probably 
	//sound bad, though...
	musicchunk = Mix_QuickLoad_RAW(music, size);
	
	//-1 means "play on the first free channel"
	Mix_PlayChannel(-1, musicchunk, 0);

	while ( !quit ) {
    	status = SDL_WaitEvent(&event);     //wait indefinitely for an event to occur
                                        //event will be removed from event queue
    	if ( !status ) {                    //Error has occured while waiting
        	printf("SDL_WaitEvent error: %s\n", SDL_GetError());
			quit = true;
        	break;
    	}
    
    	switch(event.type) {
      		case SDL_QUIT:
				quit = true;
			break;	
      		case SDL_KEYDOWN:
				key = event.key.keysym.sym;
				if ( key == SDLK_ESCAPE )      //quit if 'ESC' pressed
        	  		quit = true;
			break;
    	} 
    SDL_Delay ( 100 );			//give up some cpu time for others
  	} //while ( !quit )			//quit may be set to true when 'ESC' is pressed 
  
  
  	Mix_CloseAudio();
	return 0;
}
